package com.study.websocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class BusinessHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        super.channelRead(ctx, msg);
        FullHttpRequest request = (FullHttpRequest) msg;
        try {
            String res = "";
            String uri = request.getUri();
            ByteBuf content = request.content();
            String body = content.toString(CharsetUtil.UTF_8);
            if ("/test".equalsIgnoreCase(uri)) {
                res = "非法请求：" + uri;
                send(res, ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
            if (HttpMethod.GET.equals(request.getMethod())) {// get
                System.out.println("body=" + body);
                res = "zhaochao test";
                send(res, ctx, HttpResponseStatus.OK);
            }
        } finally {
            request.release();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
        System.out.println("有新的客户端连接");
    }

    private void send(String msg, ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.copiedBuffer(msg.getBytes()));
        response.headers().set(HttpHeaderNames.ACCEPT, "*")
                .set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); // .sync();
    }
}
